﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ECare.BUS;
using ECare.BUS.Data;
using ECare.Client.frms;

namespace ECare.Win.controls
{
    public partial class ucPlans : DevExpress.XtraEditors.XtraUserControl
    {
        public ucPlans()
        {
            InitializeComponent();


            this.grd.CellFormatting += grd_CellFormatting;
            this.grd.DataError += grd_DataError;

            this.Load += ucPlans_Load;

            this.windowsUIButtonPanel1.ButtonClick += windowsUIButtonPanel1_ButtonClick;
        }

        void windowsUIButtonPanel1_ButtonClick(object sender, DevExpress.XtraBars.Docking2010.ButtonEventArgs e)
        {
            if (e.Button.Properties.Caption == "New")
            {
                NewPlan();
            }
            else if (e.Button.Properties.Caption == "Edit")
            {
                EditPlan();
            }
            else if (e.Button.Properties.Caption == "Check")
            {
                CheckPlan();
            }
            else if (e.Button.Properties.Caption == "Cancel")
            {
                CancelPlan();
            }
            else if (e.Button.Properties.Caption == "Progress")
            {
                ShowProgress();
            }
            else if (e.Button.Properties.Caption == "Query")
            {
                this.SearchPlans();
            }
            else if (e.Button.Properties.Caption == "Execute")
            {
                this.ExecutePlan();}
            else if (e.Button.Properties.Caption == "Status")
            {
                CheckRecords();
            }
            else
            {

            }


        }

        private void CheckRecords()
        {
            if (this.grd.SelectedRows.Count == 0)
                return;
            var entitye = this.grd.SelectedRows[0].DataBoundItem as PlanInfo;
            //1....means plan.
            var frm = new frmCheckRecords {checktype = 1, entityId = entitye.plan_id};
            frm.ShowDialog();
        }


        private void ExecutePlan()
        {
            if (this.grd.SelectedRows.Count == 0)
                return;

            var selectedplan = this.grd.SelectedRows[0].DataBoundItem as PlanInfo;

            if (selectedplan.checkstatus != PlanStatus.qualified)
                return;
            bool startresult = PlanHelper.StartToExecutePlan(selectedplan);
            if (startresult == true)
            {
                //等待进行中....
                selectedplan.checkstatus = PlanStatus.pending;
                MessageBox.Show("已经转入生产.", "信息提示", MessageBoxButtons.OK);
                this.grd.Refresh();
            }
        }

        private void SearchPlans()
        {
            var frm = new frmPlanQuery();
            frm.SearchCompleted += frm_SearchCompleted;
            frm.ShowDialog();
        }
        void frm_SearchCompleted(string where)
        {
           this.LoadData(where);
        }
        private void ShowProgress()
        {
            if (this.grd.SelectedRows.Count == 0)
                return;

            var selectedplan = this.grd.SelectedRows[0].DataBoundItem as PlanInfo;

            var frm = new frmPlanDetails();
            frm.entity = selectedplan;
            frm.ShowDialog();
        }

        private void EditPlan()
        {
            if (this.grd.SelectedRows.Count == 0)
                return;
            var currentplan = this.grd.SelectedRows[0].DataBoundItem as PlanInfo;
            if (currentplan.checkstatus != PlanStatus.draft)
            {
                //不适草稿状态的 计划就不能被修改了
                MessageBox.Show("此计划已经不是草稿，不能再被编辑了.", "信息提示");
                return;
            }
            var frm = new frmPlanInfo();
            frm.entity = currentplan;
            frm.ShowDialog();
            grd.Refresh();
        }

        private void NewPlan()
        {
            var frm = new frmPlanInfo { entity = null };
            frm.Saved += frm_Saved;
            frm.ShowDialog();
        }

        private void CheckPlan()
        {
            if (this.grd.SelectedRows.Count == 0)
                return;
            var currentplan = this.grd.SelectedRows[0].DataBoundItem as PlanInfo;

            if (currentplan.checkstatus == PlanStatus.draft //草稿
                || currentplan.checkstatus == PlanStatus.rejected //被拒绝 

                || (currentplan.checkstatus == PlanStatus.qualified && currentplan.plan_IsGenerateResources == false)
                //已经审核，还没有生成领料单
                )
            {
                var frm = new frmPlanCheckInfo();
                frm.entity = currentplan;
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("当前计划不能审核.");
            }
            this.grd.Refresh();
        }

        private void CancelPlan()
        {
            if (this.grd.SelectedRows.Count == 0)
                return;

            var selectedplan = this.grd.SelectedRows[0].DataBoundItem as PlanInfo;


            if (selectedplan.checkstatus != PlanStatus.draft)
            {
                MessageBox.Show("当前计划已经被审核,不能被取消,请联系管理员.", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show("删除当前选中的计划?", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                DialogResult.No)
                return;

            var deleteresult = PlanHelper.RemovePlan(selectedplan);
            if (deleteresult)
            {//        this.source.Remove(selectedplan);}
                selectedplan.checkstatus = PlanStatus.deleted;
                this.grd.Refresh();
            }
        }


        void frm_Saved(object entity)
        {
            if (source == null)
                source = new BindingList<PlanInfo>();
            var role = entity as PlanInfo;
            var findresult = source.FirstOrDefault(a => a.plan_id == role.plan_id);
            if (findresult == null)
                this.source.Add(role);
        }
        public BindingList<PlanInfo> source { get; set; }
        void ucPlans_Load(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            formula_id.DataSource = FormulaHelper.GetFormulaInfos();
            formula_id.DisplayMember = "FormulaName";
            formula_id.ValueMember = "FormulaId";

            //plan_create_by
            var users = UserInfoHelper.GetUsers();
            plan_create_by.DataSource = users;
            plan_create_by.DisplayMember = "UserName";
            plan_create_by.ValueMember = "UserId";

            plan_check_by.DataSource = users;
            plan_check_by.DisplayMember = "UserName";
            plan_check_by.ValueMember = "UserId";

            this.LoadData("1=1");
        }

        void grd_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void grd_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && e.RowIndex < grd.Rows.Count)
            {
                if (grd.Columns[e.ColumnIndex].Name == "checkstatus")
                {
                    var currentstatus = grd.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    if (currentstatus == PlanStatus.draft.ToString())
                    {
                        this.grd.Rows[e.RowIndex].DefaultCellStyle.ForeColor = System.Drawing.Color.Blue;
                    }
                    else if (currentstatus == PlanStatus.qualified.ToString() ||
                             currentstatus == PlanStatus.pending.ToString())
                    {
                        this.grd.Rows[e.RowIndex].DefaultCellStyle.ForeColor = System.Drawing.Color.Green;
                    }
                    else if (currentstatus == PlanStatus.rejected.ToString() ||
                             currentstatus == PlanStatus.deleted.ToString())
                    {
                        this.grd.Rows[e.RowIndex].DefaultCellStyle.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {

                    }

                }
            }
        }



        private void LoadData(string where)
        {
            this.source = new BindingList<PlanInfo>(PlanHelper.GetPlans(where, false));
            this.grd.DataSource = this.source;
        }


    }
}
